require.config({
    baseUrl : 'resources/backbone',
    shim: {
    },
    paths : {
        text : "libs/text",
        router : "routers/router",
        require_utils : "utils/require_utils",
    }
});


var getRoleUserAjax = function() {
	var jsonData = {
		action : "getRole"
	};
	return $.ajax({
		url : './rule',
		type : 'GET',
		data : jsonData,
		dataType : 'json',
		success : function(dataRoleUser) {
			// selt.jsonString= data;
		}
	});
	// return jsonString;
};
var addUserAjax = function() {
	event.preventDefault();
	var jsonData = {
		action : "addUser",
		user : JSON.stringify({
			username : $("#user-name").val(),
			password : $("#password").val(),
			firstName : $("#first-name").val(),
			lastName : $("#last-name").val(),
			gender : $("#gender").val(),
			birthday : $("#birthday").val(),
			email : $("#email").val(),
			mobile : $("#mobile").val(),
			status : $("#status").val(),
		})
	};
	$.ajax({
		url : './user',
		type : 'POST',
		data : jsonData,
		dataType : 'json',
		success : function(data) {

			if (data == true) {
				alert("create accout finish!");
			}
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert(xhr.status);
			alert(thrownError);
		}
	});

};
var updateUserAjax = function() {
	var multipleValues = $("#selected-group").val() || [];
	event.preventDefault();
	var jsonData = {
		action : "updateUser",
		roleUser : multipleValues.toString(),
		user : JSON.stringify({
			username : $("#user-name").val(),
			password : $("#password").val(),
			firstName : $("#first-name").val(),
			lastName : $("#last-name").val(),
			gender : $("#gender").val(),
			birthday : $("#birthday").val(),
			email : $("#email").val(),
			mobile : $("#mobile").val(),
			status : $("#status").val(),
		})
	};
	$.ajax({
		url : './user',
		type : 'POST',
		data : jsonData,
		dataType : 'json',
		success : function(data) {

			if (data == true) {
				alert("update accout finish!");
				var router = new Router();
				router.navigate('index/view', true);
			}
		},
		error : function(xhr, ajaxOptions, thrownError) {
			alert(xhr.status);
			alert(thrownError);
		}
	});

};
var getUserAjax = function(idUser) {

	var jsonData = {
		action : "editUser",
		editID : idUser
	};
	return $.ajax({
		url : './user',
		type : 'POST',
		data : jsonData,
		dataType : 'json',
		success : function(dataGetUser) {

			// var viewEditUser=new ViewAddUser();
			// viewEditUser.render(dataGetUser);
		}
	});

};
var deleteUserAjax = function(idUser) {
	var jsonData = {
		action : "deleteUser",
		deleteID : idUser
	};
	$.ajax({
		url : './user',
		type : 'POST',
		data : jsonData,
		dataType : 'json',
		success : function(data) {
			if (data == true) {
				alert("delete success :" + idUser);
				var viewAll = new ViewAllUser();
				viewAll.render();
			} else {
				alert("delete Fail :" + idUser);
			}
		}
	});

};
var ViewAddUser = Backbone.View.extend({
	el : '#container-body',
	templateAddUser : _.template($('#user-template').html()),
	initialize : function() {
		console.log("View initialize");
	},

	render : function(data1) {
		var that = this;
		console.log("View render");
		if (data1 != null) {
			// var jsonData = {action : "getRole"};
			// $.ajax({
			// url : 'role',
			// type : 'POST',
			// data : jsonData,
			// dataType : 'json',
			// success : function(data2) {
			// var variable={User:data1,Roles:data2};
			// that.$el.html(that.templateAddUser(variable));
			// }
			// });
			$.when(getRoleUserAjax(), getUserAjax(data1)).done(
					function(dataRoleUser, dataGetUser) {

						console.log(dataGetUser.username);
						var variable = {
							User : dataGetUser[0],
							Roles : dataRoleUser[0]
						};
						that.$el.html(that.templateAddUser(variable));
					});
		} else {
			that.$el.html(this.templateAddUser);
		}
		return that;
	},

	events : {
		"click #btn-create-new" : "createUser",
		"click #btn-view-all-user" : "showAllUser",
		"click #btn-cancle-edit-user" : "cancleEditUser",
		"click #btn-ok-edit-user" : "okEditUser",
	},
	okEditUser : function() {
		updateUserAjax();
	},
	cancleEditUser : function() {
		var router = new Router();
		router.navigate('index/view', true);
	},
	createUser : function() {
		addUserAjax();
	},
	showAllUser : function() {
		var router = new Router();
		router.navigate('index/view', {
			trigger : true
		});
	}
});

var ViewAllUser = Backbone.View.extend({
	el : '#container-body',
	templateManagerUser : _.template($('#user-manager-template').html()),

	initialize : function() {
		console.log("View initialize");
	},

	render : function() {
		var that = this;
		console.log("View render");
		var jsonData = {
			action : "getAllUser"
		};
		$.ajax({
			url : './user',
			type : 'GET',
			data : jsonData,
			dataType : 'json',
			success : function(data) {
				var variable = {
					dataArray : data
				};
				that.$el.html(that.templateManagerUser(variable));
			}
		});
		return false;
	},

	events : {
		"click button[name='btn-delete-user']" : "deleteUser",
		"click button[name='btn-edit-user']" : "editUser",
	},
	deleteUser : function(e) {
		var groupId = $(e.currentTarget).attr("groupId");
		deleteUserAjax(groupId);

	},
	editUser : function(e) {
		var groupId = $(e.currentTarget).attr("groupId");
		var router = new Router();
		router.navigate('index/edit/' + groupId, {
			trigger : true
		});
	}
});


var ViewMap = Backbone.View.extend({
//	el : '#container-body',
//	templateMap : _.template($('#map-input-template').html()),

	initialize : function(options) {
		console.log("View initialize");
		this.name = PAGE_MAP_VIEW;
		/*init MAP*/
		this.setMapDefault();
		this.tpl = options.tpl;
	},

	render : function() {
//		var that = this;
//		console.log("View render");
//		that.$el.html(that.templateMap());
//		return false;
		
		var renderHtml = _.template(this.tpl, {
        });
        return this.$el.html(renderHtml);
	},

	events : {
		"click button[id='btn-add']" : "AddLocation",
		"click button[id='btn-Cancel']" : "reload",
		"click button[id='btn-delete']" : "deleteLocation",
		"click button[id='btn-change-icon']" : "changeIconMarker",
		"click a[name='btnAddLocation']" : "addLocationLink",
		"click button[id='btn-reset-marker']" : "resetMarkerLayer",
		"click button[id='btn-draw-line']" : "drawLines",
	},
	drawLines : function(){
	    OpenStreetMapUtil.drawLinesTwoPoint();
	    return false;
	},
	resetMarkerLayer : function(){
	    $('#selectMarkers option[value!=""]').remove();
	    OpenStreetMapUtil.resetMarkerLayers();
	    var lat = 10.7253272;
        var lon = 106.6175712;
        OpenStreetMapUtil.setMapCenter(lon,lat);
	    return false;
	},
	addLocationLink : function(e){
	    var locationData = $(e.currentTarget).attr("locationData");
	    var lonlat = locationData.split(",");
	    
	    
	    var lon = lonlat[1];
        var lat = lonlat[0];

        popupContentHTML = this.getPopupContentHTMLMapV2();
        var markerIcon = this.getMapMarkerAlartIcon();
        var mapEventClickMarkerhandle = function (evt){
//            alert('sdfsd');
            OpenLayers.Event.stop(evt);
        };
        
        var paramMarkerPopup = {};
//        paramMarkerPopup['boilerId'] = boiler.boilerId;
        paramMarkerPopup['lon'] = lon;
        paramMarkerPopup['lat'] = lat;
        paramMarkerPopup['popupContentHTML'] = popupContentHTML;
        paramMarkerPopup['imgUrl'] = markerIcon;
        paramMarkerPopup['mapEventClickMarkerhandle'] = mapEventClickMarkerhandle;
        paramMarkerPopup['closeBox'] = false;
        paramMarkerPopup['overflow'] = false;
        OpenStreetMapUtil.setMarkerPopup(paramMarkerPopup);
        OpenStreetMapUtil.setMapCenterPoints();
	    return false;
	},
	changeIconMarker : function(){
	    var id = $("#boiler_id").val();
        if(id != "" ){
            var imgUrl = $("#selectIcons option:selected").val();
            var param = {};
            param["id"] = id;
            param["imgUrl"] = imgUrl;
            param["popupContentHTML"] = this.getPopupContentHTMLMap();
            OpenStreetMapUtil.changeIconMarker(param);
        }
	    return false;
	},
	deleteLocation : function(){
	    var id = $("#boiler_id").val();
	    if(id != "" ){
	        OpenStreetMapUtil.removeMaker(id);
        }
	    return false;
	},
	setMapDefault : function(){
//	    $('#map-canvas').empty();
	    var lat = 10.7253272;
        var lon = 106.6175712;
        OpenStreetMapUtil.setDefaultVariable();
        OpenStreetMapUtil.initMap("map-canvas",lon,lat);
        OpenStreetMapUtil.setMapCenter(lon,lat);
	    return false;
	},
	getPopupContentHTMLMap : function () {
        
        var popupContentHTML = '<div class="row">';
        popupContentHTML +='<label class="control-label col-md-12"><h5><strong>'+ 'asdsa dfsdfdsf fsdfsd fdsf name' +'</strong>';
        popupContentHTML +='<span class="glyphicon glyphicon-remove pull-right close-icon-popup-map closePopupMap"  style="position: relative;right: -8px;top: -21px;"></span>';
        popupContentHTML +='</h5></label></div>';
        
        popupContentHTML += '<div class="row">';
        popupContentHTML +='<label class="control-label col-md-6">Luu Luong Hoi:</label>';
        popupContentHTML +='<div class="col-md-3" style="padding-left: 0px;padding-right: 0px;">';
        popupContentHTML +='<p style="text-align: right;">123</p>';
        popupContentHTML +='</div>';
        popupContentHTML +='<div class="col-md-1">';
        popupContentHTML +='<p >ton/hr</p>';
        popupContentHTML +='</div>';
        popupContentHTML +='</div>';
        
        popupContentHTML += '<div class="row">';
        popupContentHTML +='<label class="control-label col-md-6">Tong Hoi Cap Trong Ngay:</label>';
        popupContentHTML +='<div class="col-md-3" style="padding-left: 0px;padding-right: 0px;">';
        popupContentHTML +='<p style="text-align: right;">34.543589</p>';
        popupContentHTML +='</div>';
        popupContentHTML +='<div class="col-md-1">';
        popupContentHTML +='<p >ton</p>';
        popupContentHTML +='</div>';
        popupContentHTML +='</div>';
        
        popupContentHTML += '<div class="row">';
        popupContentHTML +='<label class="control-label col-md-6">Ap Suat Hoi:</label>';
        popupContentHTML +='<div class="col-md-3" style="padding-left: 0px;padding-right: 0px;">';
        popupContentHTML +='<p style="text-align: right;">3.45345678</p>';
        popupContentHTML +='</div>';
        popupContentHTML +='<div class="col-md-1">';
        popupContentHTML +='<p >Kg/cm²</p>';
        popupContentHTML +='</div>';
        popupContentHTML +='</div>';
        
        popupContentHTML += '<div class="row">';
        popupContentHTML +='<label class="control-label col-md-6">Nhiet Do Hoi:</label>';
        popupContentHTML +='<div class="col-md-3"style="padding-left: 0px;padding-right: 0px;">';
        popupContentHTML +='<p style="text-align: right;">345.678345</p>';
        popupContentHTML +='</div>';
        popupContentHTML +='<div class="col-md-1">';
        popupContentHTML +='<p >°C</p>';
        popupContentHTML +='</div>';
        popupContentHTML +='</div>';
        
        popupContentHTML += '<div class="row">';
        popupContentHTML +='<label class="control-label col-md-6">Alarm counts:</label>';
        popupContentHTML +='<div class="col-md-3" style="padding-left: 0px;padding-right: 0px;">';
        popupContentHTML +='<p style="text-align: right;">34</p>';
        popupContentHTML +='</div>';
        popupContentHTML +='</div>';
        return popupContentHTML;
    },
    getPopupContentHTMLMapV2 : function () {
        
        var popupContentHTML = '<div class="row" style="padding-left: 20px;padding-right: 0px;">';
//        popupContentHTML +='<img src="' + this.getMapNodeIcon() + '">';
        popupContentHTML +='<label class="control-label col-md-12"><h5><img src="' + this.getMapNodeIcon() + '"><strong> '+ 'VINA CAFE LONG THANH - BOILER 01' +'</strong>';
        popupContentHTML +='<span class="glyphicon glyphicon-remove pull-right close-icon-popup-map closePopupMap"  style="position: relative;right: -8px;top: -21px;"></span>';
        popupContentHTML +='</h5></label></div>';
        
        popupContentHTML += '<div class="row" style="padding-left: 20px;padding-right: 0px;">';
        popupContentHTML +='<div class="col-md-7">';
        popupContentHTML +='<img src="' + this.getMapBoilerIcon() + '">  '+'boiler 9';
        popupContentHTML +='</div>';
        popupContentHTML +='<div class="col-md-5">';
        popupContentHTML +='<img src="' + this.getMapAlarmIcon() + '">  '+'12';
        popupContentHTML +='</div>';
        popupContentHTML +='</div>';
        
        popupContentHTML +='</br>';
        popupContentHTML +='</br>';
        
        popupContentHTML += '<div class="form-horizontal col-md-12" style="padding-left: 0px;padding-right: 0px;">';
        
        // start area 1
        popupContentHTML += '<div class="col-md-3" style="padding-left: 0px;padding-right: 0px;">';
        popupContentHTML += '<div class="col-md-12 popup-sub-area-value" style="padding-left: 0px;padding-right: 0px;background-color: #bdc1c4;">';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
        popupContentHTML += 'Steam';
        popupContentHTML += '</div>';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
        popupContentHTML += 'total';
        popupContentHTML += '</div>';
        popupContentHTML += '<hr style="margin-top: 2px;margin-bottom: 5px;">';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="color: #1bade1;text-align: center;margin: 0 auto;">';
        popupContentHTML += '123456789.45';
        popupContentHTML += '</div>';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
        popupContentHTML += 'ton';
        popupContentHTML += '</div>';
        popupContentHTML += '</div>';
        popupContentHTML += '</div>';
        // end area 1
        // start area 2
        popupContentHTML += '<div class="col-md-3" style="padding-left: 5px;padding-right: 0px;">';
        popupContentHTML += '<div class="col-md-12 popup-sub-area-value" style="padding-left: 0px;padding-right: 0px;background-color: #bdc1c4;">';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
        popupContentHTML += 'Steam';
        popupContentHTML += '</div>';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
        popupContentHTML += 'flow';
        popupContentHTML += '</div>';
        popupContentHTML += '<hr style="margin-top: 2px;margin-bottom: 5px;">';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="color: #1bade1;text-align: center;margin: 0 auto;">';
        popupContentHTML += '123456789.98';
        popupContentHTML += '</div>';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
        popupContentHTML += 'ton/h';
        popupContentHTML += '</div>';
        popupContentHTML += '</div>';
        popupContentHTML += '</div>';
        // end area 2
        // start area 3
        popupContentHTML += '<div class="col-md-3" style="padding-left: 5px;padding-right: 0px";>';
        popupContentHTML += '<div class="col-md-12 popup-sub-area-value" style="padding-left: 0px;padding-right: 0px;background-color: #bdc1c4;">';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
        popupContentHTML += 'Steam';
        popupContentHTML += '</div>';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
        popupContentHTML += 'pressure';
        popupContentHTML += '</div>';
        popupContentHTML += '<hr style="margin-top: 2px;margin-bottom: 5px;">';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="color: #1bade1;text-align: center;margin: 0 auto;">';
        popupContentHTML += '123456789.89';
        popupContentHTML += '</div>';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
        popupContentHTML += 'kg/cm2';
        popupContentHTML += '</div>';
        popupContentHTML += '</div>';
        popupContentHTML += '</div>';
        // end area 3
        // start area 4
        popupContentHTML += '<div class="col-md-3" style="padding-left: 5px;padding-right: 0px;">';
        popupContentHTML += '<div class="col-md-12 popup-sub-area-value" style="padding-left: 0px;padding-right: 0px;background-color: #bdc1c4;">';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
        popupContentHTML += 'Steam';
        popupContentHTML += '</div>';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
        popupContentHTML += 'temperature';
        popupContentHTML += '</div>';
        popupContentHTML += '<hr style="margin-top: 2px;margin-bottom: 5px;">';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="color: #1bade1;text-align: center; margin: 0 auto;">';
        popupContentHTML += '123456789.98';
        popupContentHTML += '</div>';
        popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center; margin: 0 auto;">';
        popupContentHTML += 'ton';
        popupContentHTML += '</div>';
        popupContentHTML += '</div>';
        popupContentHTML += '</div>';
        // end area 4
        popupContentHTML +='</div>';
        popupContentHTML +='</div>';
        

        return popupContentHTML;
    },
    getMapBoilerIcon : function(){
        return 'resources/img/detail boiler-04.png';
    },
    getMapAlarmIcon : function(){
        return 'resources/img/map-04.png';
    },
    getMapNodeIcon : function(){
        return 'resources/img/node.png';
    },
    getMapMarkerIcon : function(){
        return 'resources/img/boiler_33px.png';
    },
    getMapMarkerAlartIcon : function(){
        return 'resources/img/boiler alert.gif';
    },
	AddLocation : function() {
		
		var lon = $('#lon').val();
		var lat = $('#lat').val();

        popupContentHTML = this.getPopupContentHTMLMapV2();
        var markerIcon = this.getMapMarkerAlartIcon();
        var mapEventClickMarkerhandle = function (evt){
//            alert('sdfsd');
            OpenLayers.Event.stop(evt);
        };

        
        var paramMarkerPopup = {};
//        paramMarkerPopup['boilerId'] = boiler.boilerId;
        paramMarkerPopup['lon'] = lon;
        paramMarkerPopup['lat'] = lat;
        paramMarkerPopup['popupContentHTML'] = popupContentHTML;
        paramMarkerPopup['imgUrl'] = markerIcon;
        paramMarkerPopup['mapEventClickMarkerhandle'] = mapEventClickMarkerhandle;
        paramMarkerPopup['closeBox'] = true;
        paramMarkerPopup['overflow'] = false;
        OpenStreetMapUtil.setMarkerPopup(paramMarkerPopup);
        
        OpenStreetMapUtil.setMapCenterPoints();
	},
	reload : function() {
	    $('#selectMarkers option[value!=""]').remove();
	    this.setMapDefault();
	}
});

var Router = Backbone.Router.extend({
	initialize : function() {
	    this.currentView = "";
		console.log("Router initialize");
	},
	index : function() {
		console.log("The index router");
	},
	routes : {
		"" : "index",
		"index" : "index",
		"index/view" : "viewAll",
		"index/edit/:id" : "editUser",
		"index/view/*path" : "showImage"
	},
	editUser : function(id) {
		var viewEditUser = new ViewAddUser();
		viewEditUser.render(id);
	},
	insertUser : function() {
		addUserAjax();
	},
	index : function() {

		var viewMap = new ViewMap();
		viewMap.render();
	},
	viewAll : function() {
		var viewAll = new ViewAllUser();
		viewAll.render();

	},

});
var OpenStreetMapUtil = function() {
    /*KEY WORD OpenLayer.Util write to console web brower*/
    var map = null;
    var zoom = 18;
    var markers = null;
//    var layer = null;
    var cirlceLayer = null;
    var vectorLayer = null;
    var arrPointMarker = [];
    var currentPopup = null;
    var popupClass = null;
    var sizeIconMarker = null;
    // save current map view
    var currentZoom = null;
    var currentPointMapCenter = null;
    var isSaveMapView = false;
    //----------------------
    var divContainer = null;
    return {
        isSaveMapView : function (){
            return isSaveMapView;
        },
        saveCurrentMapView : function(){
            if(map != null){
                isSaveMapView = true;
                currentZoom = map.getZoom();
                currentPointMapCenter = map.getCenter();
            }
        },
        showCurrentMapView : function(){
            if(map != null && currentZoom != null 
                    && currentPointMapCenter != null
                    && isSaveMapView){
                    map.setCenter(currentPointMapCenter,currentZoom);
                    isSaveMapView = false;
                    currentZoom = null;
                    currentPointMapCenter = null;
            }
        },
        initMap : function(container,lon,lat){
            var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
            var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
            var position = new OpenLayers.LonLat(lon, lat).transform( fromProjection, toProjection);
            popupClass = new OpenLayers.Class(OpenLayers.Popup.Anchored, {
                  "autoSize": true,
                  "minSize": new OpenLayers.Size(350, 170),
                  "maxSize": new OpenLayers.Size(450, 220),
                  "keepInMap": true
            });
            sizeIconMarker = new OpenLayers.Size(33,33);
            divContainer = container;
            
            // Layerstyle
            cirlceLayer = new OpenLayers.Layer.Vector('cirlceLayer', {
                styleMap: new OpenLayers.StyleMap({
                  "default": new OpenLayers.Style({
//                    pointRadius: "${radius}",
                    pointRadius: "${getSize}",
                    fillColor: '#bdc1c4',
                    fillOpacity: 0.6,
                    strokeColor: '#ed9576',
                    strokeWidth: 1,
                    strokeOpacity: 0.9
                  },
                  { context: {
                      getSize: function(feature) {
                          return 500 / feature.layer.map.getResolution();
                      }}  
                  })
                })
              });
            var vlayer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
            vlayer_style.fillOpacity = 0.6;
            vlayer_style.fillColor = "green";
            vlayer_style.strokeWidth = 6;
            vlayer_style.strokeColor = "blue";
            vlayer_style.strokeOpacity = 1;

            var select_style = OpenLayers.Util.extend({}, vlayer_style);
            select_style.fillOpacity = 0.6;
            select_style.strokeWidth = 10;
            select_style.strokeColor = "black";
            select_style.fillColor = "black";
            vlayer_style.strokeOpacity = 1;
            
            var vStyleMap = new OpenLayers.StyleMap( {
               "default" : vlayer_style,
               "select" : select_style
            });
            
            vectorLayer = new OpenLayers.Layer.Vector("vectorLayer"
                    , {styleMap: vStyleMap});
            
            map = new OpenLayers.Map({
                div: container,
            //  allOverlays: true,
                theme: null,
                projection: new OpenLayers.Projection("EPSG:900913"),
                displayProjection: new OpenLayers.Projection("EPSG:4326"),
                units: 'm',
                numZoomLevels: 18,
                maxResolution: 156543.0339,
                maxExtent: new OpenLayers.Bounds(
                    -20037508.34, -20037508.34, 20037508.34, 20037508.34
                ),
                controls: [
                    //new OpenLayers.Control.Permalink(),
                    //new OpenLayers.Control.LayerSwitcher(),
                    //new OpenLayers.Control.MousePosition(),
                    //new OpenLayers.Control.Attribution(),
                    new OpenLayers.Control.Navigation(),
                    // new OpenLayers.Control.PanZoom(),
                    new OpenLayers.Control.PanZoomBar(),
                    new OpenLayers.Control.MousePosition({
                        "numDigits": 8,
                        displayProjection: new  OpenLayers.Projection("EPSG:4326"),
                        emptyString:"outside the map" }),
                ],
                layers: [
//                    new OpenLayers.Layer.OSM('OSM OpenStreetMap', null),
                    new OpenLayers.Layer.Google("Google ", { 
                       // type : google.maps.MapTypeId.ROADMAP,
//                      type : google.maps.MapTypeId.TERRAIN,
                        sphericalMercator: true,
                        projection:"EPSG:900913",
                        transparent: true }),
                        vectorLayer,
                        cirlceLayer,
                ],
                center: position,
                zoom : zoom
            });
          
        },
        resetMarkerLayers : function(){
            if(markers.markers.length > 0 && markers != null){
                for(var i = 0 ; i < markers.markers.length ; i++){
                    markers.removeMarker(markers.markers[i]);
                }
            }
//            markers.markers.clearMarkers();
        },
        setMapCenter : function(lon,lat){
            var fromProjection = new OpenLayers.Projection("EPSG:4326");   // Transform from WGS 1984
            var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
            var position = new OpenLayers.LonLat(lon, lat).transform( fromProjection, toProjection);
            map.setCenter(position, 17);
        },
        setMapCenterPoints : function(){
            var lngMin = parseFloat(this.getLngMin());
            var lngMax = parseFloat(this.getLngMax());
            var latMin = parseFloat(this.getLatMin());
            var latMax = parseFloat(this.getLatMax());
            var centerPoint = this.caculateCenterPoint(latMin,lngMin,
                    latMax,lngMax,arrPointMarker.length);
            map.setCenter(centerPoint, zoom);
        },
        setMarkerIcon : function(lon,lat,imgUrl,eventHandle){
            
            if(map !== null){
                if(markers === null){
                    markers = new OpenLayers.Layer.Markers( "Markers" );
                    map.addLayer(markers);
                }
//              var size = new OpenLayers.Size(33,33);
                var offset = new OpenLayers.Pixel(-(sizeIconMarker.w), -sizeIconMarker.h);
                var icon = new OpenLayers.Icon(imgUrl,sizeIconMarker,offset);
                
                var lonLatIcon = new OpenLayers.LonLat(lon,lat).transform(
                        new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                        map.getProjectionObject() // to Spherical Mercator Projection
                );
                
                var markerIcon = new OpenLayers.Marker(lonLatIcon,icon);
                markerIcon.events.register( 'click', markers, eventHandle);
                markers.addMarker(markerIcon);
            }
        },
        setMarkerPopup : function(paramMarkerPopup){
            if(map !== null){
                if(markers === null){
                    markers = new OpenLayers.Layer.Markers( "Markers" );
                    map.addLayer(markers);
                }
                
                var lonlatArr = [] || '';
                lonlatArr.push(paramMarkerPopup.lon);
                lonlatArr.push(paramMarkerPopup.lat);

                arrPointMarker.push(lonlatArr);
                
                var lonLatMarker = new OpenLayers.LonLat(paramMarkerPopup.lon, paramMarkerPopup.lat)
                    .transform(new OpenLayers.Projection("EPSG:4326"), 
                    map.getProjectionObject());
                var feature = new OpenLayers.Feature(markers, lonLatMarker); 
//                feature.style = {
//                        strokeColor: "#00FF00",
//                        strokeOpacity: 1,
//                        strokeWidth: 2,
//                        fillColor: "#FF5500",
//                        fillOpacity: 0.5,
//                        pointRadius: 6,
//                        pointerEvents: "visiblePainted"
//                };
                feature.closeBox = paramMarkerPopup.closeBox;
                feature.popupClass = popupClass;
                feature.data.popupContentHTML = paramMarkerPopup.popupContentHTML;
                feature.data.overflow = (paramMarkerPopup.overflow) ? "auto" : "hidden";
                
                
                var offset = new OpenLayers.Pixel(-(sizeIconMarker.w), -sizeIconMarker.h);
                var icon = new OpenLayers.Icon(paramMarkerPopup.imgUrl,sizeIconMarker,offset);
                var lonLatIcon = new OpenLayers.LonLat(paramMarkerPopup.lon,paramMarkerPopup.lat).transform(
                        new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                        map.getProjectionObject() // to Spherical Mercator Projection
                );
                var marker = new OpenLayers.Marker(lonLatIcon, icon.clone());
                marker.feature = feature;
                    
                //marker = this.registerPopupMouseOutOver(feature, marker);
                marker = this.registerPopupMouseClick(feature, marker);
                //marker.events.register("click", feature,paramMarkerPopup.mapEventClickMarkerhandle);
                // add new start
                var idBoiler = "boiler"+ markers.markers.length;
                var nameBoiler = "Marker "+ markers.markers.length;
                marker.id = idBoiler ;
                $('#selectMarkers').append('<option value="' + idBoiler + '">' + nameBoiler + '</option>');
                // add new start
                
                markers.addMarker(marker);
            }
        },
        //add new START
        removeMaker : function(id){
            for(var i = 0 ; i < markers.markers.length ; i++){
                if(markers.markers[i].id == id){
                    markers.removeMarker(markers.markers[i]);
//                    var imgUrl = 'resources/img/boiler_33px.png';
//                    var offset = new OpenLayers.Pixel(-(sizeIconMarker.w), -sizeIconMarker.h);
//                    var icon = new OpenLayers.Icon(imgUrl,sizeIconMarker,offset);
//                    markers.markers[i].icon = icon;
                }
            }
            //============================
            $("#boiler_id").val("");
            $("#selectMarkers option[value='"+id+"']").remove();
        },
        changeIconMarker : function(param){
            var marker = null;
            for(var i = 0 ; i < markers.markers.length ; i++){
                if(markers.markers[i].id == param.id){
                    //keep old marker
                    marker = markers.markers[i];
                    //remove marker from array markers from object map
                    markers.removeMarker(markers.markers[i]);
                }
            }
            if(marker != null){
                //create new icon object
                var offset = new OpenLayers.Pixel(-(sizeIconMarker.w), -sizeIconMarker.h);
                var icon = new OpenLayers.Icon(param.imgUrl,sizeIconMarker,offset);
                //keep old feature object from marker do you want
                //change icon
                var feature = marker.feature;
                if(param.popupContentHTML !== undefined){
                    feature.data.popupContentHTML = param.popupContentHTML;
                    if(feature.popup != null){
                        feature.popup.destroy();
                        feature.popup = null;
                    }
                }
                // set again new icon and feature object of marker do you want change
                var newMarker = new OpenLayers.Marker(marker.lonlat, icon.clone());
                newMarker.feature = feature;
                
//                delete marker.feature;
                newMarker.id = marker.id;
                //newMarker = this.registerPopupMouseOutOver(feature,newMarker);
                
                //register again click handle old marker 
                //to new merker
                newMarker = this.registerPopupMouseClick(feature,newMarker);
                markers.addMarker(newMarker);
            } else {
                alert('please chose marker!');
            }
        },
        registerPopupMouseClick : function(feature,marker){
            marker.events.register("click", feature,function(evt){
                if (this.popup === null) {
                    this.popup = this.createPopup(this.closeBox);
                    //add New start
                    // this.popup.id = marker.id;
                    //add New end
                    map.addPopup(this.popup);
                    this.popup.show();
                } else {
                        this.popup.toggle();
                }
                // start for handle click of icon close popup marker 
                var selt = this;
                if(selt.popup != null){
                    var currentPopupId = selt.popup.id;
                    // FOR CASE 01
//                    $('#' + currentPopupId).click(function(){
//                        $('#' + currentPopupId).css("z-index",999);
//                        for(var i = 0 ; i < map.popups.length ; i++){
//                            if( currentPopupId != map.popups[i].id){
//                                $('#' + map.popups[i].id).css("z-index",998);
//                            }
//                        }
//                    });
                    // FOR CASE 02
                    for(var i = 0 ; i < map.popups.length ; i++){
                        if( currentPopupId != map.popups[i].id){
                            //remove from list popups map object
                            var popupId = map.popups[i].id;
                            map.removePopup(map.popups[i]);
                            for(var i = 0 ; i < markers.markers.length ; i++){
                                var fature = markers.markers[i].feature;
                                if(fature.popup !== null){
                                    if(fature.popup.id === popupId){
                                        fature.popup.destroy();
                                        fature.popup = null;
                                    }
                                }
                            }
                        }
                    }
                    //FOR CLICK ICON CLOSE POPUP MARKER
                    $('#' + currentPopupId).find(".close-icon-popup-map").click(function(){
                        for(var i = 0 ; i < map.popups.length ; i++){
                            if( currentPopupId == map.popups[i].id){
                                //remove from list popups map object
                                map.removePopup(selt.popup);
                                //destroy popup from feature object
                                selt.popup.destroy();
                                selt.popup = null;
                            }
                        }
                    });
                }
                // end for handle click of icon close popup marker 
                currentPopup = this.popup;
                OpenLayers.Event.stop(evt);
            });
            return marker;
        },
        updateInfoMarkersMap : function(){
            if(markers != null){
                if(markers.markers.length > 0){
                    var normalBoiler = 'resources/img/boiler_33px.png';
                    var alertBoiler = 'resources/img/map-04.png';
                    cirlceLayer.removeAllFeatures();
                    for(var i = 0 ; i < markers.markers.length ; i++){
                        var hasAlarm = Boolean(Math.round(Math.random()));
                        var param = {};
                        param["id"] = markers.markers[i].id;
                        if(hasAlarm){
                            param["imgUrl"] = alertBoiler;
                            param["popupContentHTML"] = this.getPopupContentHTMLMap();
                        }else{
                            var param2 = {};
                            param2["lonlat"] = markers.markers[i].lonlat;
                            param2["radius"] = 50;
                            OpenStreetMapUtil.drawCirlceAroundMarker(param2);
                            
                            param["imgUrl"] = alertBoiler;
                            param["popupContentHTML"] = this.getPopupContentHTMLMapV2();
                        }
                        OpenStreetMapUtil.changeIconMarker(param);
                    }
                }
            }
        },
        registerPopupMouseOutOver : function(feature,marker){
            //show popup when mouse over and 
            //destroy when mouse out
            marker.events.register("mouseover", feature, function(evt){
                if (this.popup === null) {
                      this.popup = this.createPopup(this.closeBox);
                      map.addPopup(this.popup);
                      this.popup.show();
                } else {
                      this.popup.toggle();
                }
                currentPopup = this.popup;
                OpenLayers.Event.stop(evt);
            });

            marker.events.register("mouseout", feature, function(evt){
                map.removePopup(this.popup);
                this.popup.destroy();
                this.popup = null;
                OpenLayers.Event.stop(evt);
            });
            return marker;
        },
        drawLinesTwoPoint : function(){
            var arrPoint = [];
            var start_point = new OpenLayers.Geometry.Point(0,10);
            var end_point = new OpenLayers.Geometry.Point(30,0);
            start_point.transform(
                new OpenLayers.Projection("EPSG:4326"),
                new OpenLayers.Projection("EPSG:900913")
            ); 
            end_point.transform(
                new OpenLayers.Projection("EPSG:4326"),
                new OpenLayers.Projection("EPSG:900913")
            ); 
            arrPoint.push(start_point);
            arrPoint.push(end_point);
            
          //create SelectFeatures
            var selectControl = new OpenLayers.Control.SelectFeature(vectorLayer,
                {displayClass: "selectButton", 
                title: 'Select Ways', 
                onSelect: function(){alert("select");}, 
                onUnselect: function(){alert("deselect");},
                toggle:false,
                clickout:true,
                multiple:false,
                hover:false,
                toggleKey:"ctrlKey",
                multipleKey:"shiftKey",
                geometryTypes: ["OpenLayers.Geometry.LineString"],
                callbacks: {
                    'over': function(feature){ feature.layer.div.style.cursor = "crosshair"; },
                    'out': function(feature){ feature.layer.div.style.cursor = ""; }
                }
            });
            map.addControl(selectControl);
            selectControl.activate();
            
            var line = new OpenLayers.Geometry.LineString(arrPoint);    
            var lineF = new OpenLayers.Feature.Vector(line,null);
            vectorLayer.addFeatures([lineF]);
            map.zoomToMaxExtent(vectorLayer.getDataExtent());
        },
        drawCirlceAroundMarker : function(param){
            if(param.lonlat != undefined && param.radius != undefined){
                var lonLat = param.lonlat;
                
                var feature = new OpenLayers.Feature.Vector(
                    new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat),
                    {
                      radius : param.radius
                    }
                );
                
                cirlceLayer.addFeatures([feature]);
//                map.zoomToMaxExtent(vectorLayer.getDataExtent());
            }
        },
        
        getPopupContentHTMLMap : function () {
            
            var popupContentHTML = '<div class="row">';
            popupContentHTML +='<label class="control-label col-md-12"><h5><strong>'+ 'asdsa dfsdfdsf fsdfsd fdsf name' +'</strong>';
            popupContentHTML +='<span class="glyphicon glyphicon-remove pull-right close-icon-popup-map closePopupMap"  style="position: relative;right: -8px;top: -21px;"></span>';
            popupContentHTML +='</h5></label></div>';
            
            popupContentHTML += '<div class="row">';
            popupContentHTML +='<label class="control-label col-md-6">Luu Luong Hoi:</label>';
            popupContentHTML +='<div class="col-md-3" style="padding-left: 0px;padding-right: 0px;">';
            popupContentHTML +='<p style="text-align: right;">123</p>';
            popupContentHTML +='</div>';
            popupContentHTML +='<div class="col-md-1">';
            popupContentHTML +='<p >ton/hr</p>';
            popupContentHTML +='</div>';
            popupContentHTML +='</div>';
            
            popupContentHTML += '<div class="row">';
            popupContentHTML +='<label class="control-label col-md-6">Tong Hoi Cap Trong Ngay:</label>';
            popupContentHTML +='<div class="col-md-3" style="padding-left: 0px;padding-right: 0px;">';
            popupContentHTML +='<p style="text-align: right;">34.543589</p>';
            popupContentHTML +='</div>';
            popupContentHTML +='<div class="col-md-1">';
            popupContentHTML +='<p >ton</p>';
            popupContentHTML +='</div>';
            popupContentHTML +='</div>';
            
            popupContentHTML += '<div class="row">';
            popupContentHTML +='<label class="control-label col-md-6">Ap Suat Hoi:</label>';
            popupContentHTML +='<div class="col-md-3" style="padding-left: 0px;padding-right: 0px;">';
            popupContentHTML +='<p style="text-align: right;">3.45345678</p>';
            popupContentHTML +='</div>';
            popupContentHTML +='<div class="col-md-1">';
            popupContentHTML +='<p >Kg/cm²</p>';
            popupContentHTML +='</div>';
            popupContentHTML +='</div>';
            
            popupContentHTML += '<div class="row">';
            popupContentHTML +='<label class="control-label col-md-6">Nhiet Do Hoi:</label>';
            popupContentHTML +='<div class="col-md-3"style="padding-left: 0px;padding-right: 0px;">';
            popupContentHTML +='<p style="text-align: right;">345.678345</p>';
            popupContentHTML +='</div>';
            popupContentHTML +='<div class="col-md-1">';
            popupContentHTML +='<p >°C</p>';
            popupContentHTML +='</div>';
            popupContentHTML +='</div>';
            
            popupContentHTML += '<div class="row">';
            popupContentHTML +='<label class="control-label col-md-6">Alarm counts:</label>';
            popupContentHTML +='<div class="col-md-3" style="padding-left: 0px;padding-right: 0px;">';
            popupContentHTML +='<p style="text-align: right;">34</p>';
            popupContentHTML +='</div>';
            popupContentHTML +='</div>';
            return popupContentHTML;
        },
        getPopupContentHTMLMapV2 : function () {
            
            var popupContentHTML = '<div class="row" style="padding-left: 20px;padding-right: 0px;">';
//            popupContentHTML +='<img src="' + this.getMapNodeIcon() + '">';
            popupContentHTML +='<label class="control-label col-md-12"><h5><img src="resources/img/node.png"><strong> '+ 'VINA CAFE LONG THANH - BOILER 01' +'</strong>';
            popupContentHTML +='<span class="glyphicon glyphicon-remove pull-right close-icon-popup-map closePopupMap"  style="position: relative;right: -8px;top: -21px;"></span>';
            popupContentHTML +='</h5></label></div>';
            
            popupContentHTML += '<div class="row" style="padding-left: 20px;padding-right: 0px;">';
            popupContentHTML +='<div class="col-md-7">';
            popupContentHTML +='<img src="resources/img/detail boiler-04.png">  '+'boiler 9';
            popupContentHTML +='</div>';
            popupContentHTML +='<div class="col-md-5">';
            popupContentHTML +='<img src="resources/img/map-04.png">  '+'12';
            popupContentHTML +='</div>';
            popupContentHTML +='</div>';
            
            popupContentHTML +='</br>';
            popupContentHTML +='</br>';
            
            popupContentHTML += '<div class="form-horizontal col-md-12" style="padding-left: 0px;padding-right: 0px;">';
            
            // start area 1
            popupContentHTML += '<div class="col-md-3" style="padding-left: 0px;padding-right: 0px;">';
            popupContentHTML += '<div class="col-md-12 popup-sub-area-value" style="padding-left: 0px;padding-right: 0px;background-color: #bdc1c4;">';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
            popupContentHTML += 'Steam';
            popupContentHTML += '</div>';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
            popupContentHTML += 'total';
            popupContentHTML += '</div>';
            popupContentHTML += '<hr style="margin-top: 2px;margin-bottom: 5px;">';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="color: #1bade1;text-align: center;margin: 0 auto;">';
            popupContentHTML += '123456789.45';
            popupContentHTML += '</div>';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
            popupContentHTML += 'ton';
            popupContentHTML += '</div>';
            popupContentHTML += '</div>';
            popupContentHTML += '</div>';
            // end area 1
            // start area 2
            popupContentHTML += '<div class="col-md-3" style="padding-left: 5px;padding-right: 0px;">';
            popupContentHTML += '<div class="col-md-12 popup-sub-area-value" style="padding-left: 0px;padding-right: 0px;background-color: #bdc1c4;">';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
            popupContentHTML += 'Steam';
            popupContentHTML += '</div>';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
            popupContentHTML += 'flow';
            popupContentHTML += '</div>';
            popupContentHTML += '<hr style="margin-top: 2px;margin-bottom: 5px;">';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="color: #1bade1;text-align: center;margin: 0 auto;">';
            popupContentHTML += '123456789.98';
            popupContentHTML += '</div>';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
            popupContentHTML += 'ton/h';
            popupContentHTML += '</div>';
            popupContentHTML += '</div>';
            popupContentHTML += '</div>';
            // end area 2
            // start area 3
            popupContentHTML += '<div class="col-md-3" style="padding-left: 5px;padding-right: 0px";>';
            popupContentHTML += '<div class="col-md-12 popup-sub-area-value" style="padding-left: 0px;padding-right: 0px;background-color: #bdc1c4;">';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
            popupContentHTML += 'Steam';
            popupContentHTML += '</div>';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
            popupContentHTML += 'pressure';
            popupContentHTML += '</div>';
            popupContentHTML += '<hr style="margin-top: 2px;margin-bottom: 5px;">';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="color: #1bade1;text-align: center;margin: 0 auto;">';
            popupContentHTML += '123456789.89';
            popupContentHTML += '</div>';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
            popupContentHTML += 'kg/cm2';
            popupContentHTML += '</div>';
            popupContentHTML += '</div>';
            popupContentHTML += '</div>';
            // end area 3
            // start area 4
            popupContentHTML += '<div class="col-md-3" style="padding-left: 5px;padding-right: 0px;">';
            popupContentHTML += '<div class="col-md-12 popup-sub-area-value" style="padding-left: 0px;padding-right: 0px;background-color: #bdc1c4;">';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
            popupContentHTML += 'Steam';
            popupContentHTML += '</div>';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center;margin: 0 auto;">';
            popupContentHTML += 'temperature';
            popupContentHTML += '</div>';
            popupContentHTML += '<hr style="margin-top: 2px;margin-bottom: 5px;">';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="color: #1bade1;text-align: center; margin: 0 auto;">';
            popupContentHTML += '123456789.98';
            popupContentHTML += '</div>';
            popupContentHTML += '<div class="row col-md-12 span12 pagination-centered" style="text-align: center; margin: 0 auto;">';
            popupContentHTML += 'ton';
            popupContentHTML += '</div>';
            popupContentHTML += '</div>';
            popupContentHTML += '</div>';
            // end area 4
            popupContentHTML +='</div>';
            popupContentHTML +='</div>';

            return popupContentHTML;
        },
        //add new END
        caculateCenterPoint : function(_minLat, _minLng, _maxLat, _maxLng, _markerCount){
            // --- set zoom level
            if(_markerCount == 1){
                zoomLevel = 14;
            }
            else{
                var latDistance = Math.abs(_maxLat - _minLat);
                var lngDistance = Math.abs(_maxLng - _minLng);
                var markerDistance = Math.sqrt(Math.pow(latDistance,2) + Math.pow(lngDistance,2));
                 
//              if(markerDistance >= 180){
//                  zoom = 1;
//              }
//              else if(markerDistance >= 150){
//                  zoom = 1.5;
//              }
//              else if(markerDistance >= 125){
//                  zoom = 2;
//              }
//              else if(markerDistance >= 22.5){
//                  zoom = 2.5;
//              }
//              else if(markerDistance >= 11.25){
//                  zoom = 3;
//              }
//              else if(markerDistance >= 5.625){
//                  zoom = 3.5;
//              }
//              else if(markerDistance >= 2.813){
//                  zoom = 4;
//              }
//              else if(markerDistance >= 1.406){
//                  zoom = 5;
//              }
//              else if(markerDistance >= 0.703){
//                  zoom = 6;
//              }
//              else if(markerDistance >= 0.301){
//                  zoom = 6.5;
//              }
//              //------------------------------
//              else if(markerDistance >= 0.150){
//                  zoom = 12;
//              }
//              else if(markerDistance >= 0.075){
//                  zoom = 11;
//              }
//              else if(markerDistance >= 0.037){
//                  zoom = 13;
//              }
//              else if(markerDistance >= 0.01){
//                  zoom = 13.5;
//              }
//              else if(markerDistance >= 0.0025){
//                  zoom = 14;
//              }
//              //--------------------------------
                if(markerDistance >= 180){
                    zoom = 1;
                }
                else if(markerDistance >= 150){
                    zoom = 1.5;
                }
                else if(markerDistance >= 125){
                    zoom = 2;
                }
                else if(markerDistance >= 22.5){
                    zoom = 2.5;
//                    zoom = 1.5;
                }
                else if(markerDistance >= 11.25){
                   // zoom = 3;
                    zoom = 5;
                }
                else if(markerDistance >= 5.625){
                    //zoom = 3.5;
                    zoom = 5.5;
                }
                else if(markerDistance >= 2.813){
                    //zoom = 4;
                    zoom = 6.5;
                }
                else if(markerDistance >= 1.406){
                    //zoom = 5;
                    zoom = 7.5;
                }
                else if(markerDistance >= 0.703){
                    //zoom = 6;
                    zoom = 8.5;
                }
                else if(markerDistance >= 0.301){
                    //zoom = 6.5;
                    zoom = 10;
                }
                //------------------------------
                else if(markerDistance >= 0.150){
                    zoom = 12;
                }
                else if(markerDistance >= 0.075){
                    zoom = 11;
                }
                else if(markerDistance >= 0.037){
                    zoom = 13;
                }
                else if(markerDistance >= 0.015){
                    zoom = 13.5;
                }
                else if(markerDistance >= 0.0025){
                    zoom = 14;
                }
                //--------------------------------
            }
             
            // --- calculate center point location
            var centerLat = 0;
            var difLatFlg = ((_minLat*_maxLat) > 0 ? 1 : -1);
            if(difLatFlg > 0){
                centerLat = (_minLat + _maxLat)/2;
            }
            else{
                centerLat = (Math.abs(_minLat) + Math.abs(_maxLat))/2 + _minLat;
            }
             
            var centerLng = 0;
            var difLngFlg = (_minLng*_maxLng > 0 ? 1 : -1);
            if(difLngFlg > 0){
                centerLng = (_minLng + _maxLng)/2;
            }
            else{
                centerLng = (Math.abs(_minLng) + Math.abs(_maxLng))/2 + _minLng;
            }
             
            var centerPoint = new OpenLayers.LonLat(centerLng, centerLat)
                .transform(
                    new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                    map.getProjectionObject() // to Spherical Mercator Projection
                );
            return centerPoint;
        },
        getLngMin : function(){
            var temp = arrPointMarker[0][0];
            for(var i=0 ;i<arrPointMarker.length;i++){
                if(parseFloat(arrPointMarker[i][0]) < parseFloat(temp)){
                    temp = arrPointMarker[i][0];
                }
            }
            return temp;
        },
        getLngMax : function(){
            var temp = arrPointMarker[0][0];
            for(var i=0 ;i<arrPointMarker.length;i++){
                if(parseFloat(arrPointMarker[i][0]) > parseFloat(temp)){
                    temp = arrPointMarker[i][0];
                }
            }
            return temp;
        },
        getLatMin : function(){
            var temp = arrPointMarker[0][1];
            for(var i=0 ;i<arrPointMarker.length;i++){
                if(parseFloat(arrPointMarker[i][1]) < parseFloat(temp)){
                    temp = arrPointMarker[i][1];
                }
            }
            return temp;
        },
        getLatMax : function(){
            var temp = arrPointMarker[0][1];
            for(var i=0 ;i<arrPointMarker.length;i++){
                if(parseFloat(arrPointMarker[i][1]) > parseFloat(temp)){
                    temp = arrPointMarker[i][1];
                }
            }
            return temp;
        },
        setDefaultVariable : function(){
            if (divContainer != null){
                $('#'+divContainer).empty();
            }
            arrPointMarker = [];
            map = null;
            zoom = 18;
            markers = null;
            currentPopup = null;
            popupClass = null;
            sizeIconMarker = null;
        },
        gc : function(){
            delete divContainer;
            delete arrPointMarker;
            delete map;
            delete zoom;
            delete markers;
            delete currentPopup;
            delete popupClass;
            delete sizeIconMarker;
            delete currentZoom;
            delete currentPointMapCenter;
            delete isSaveMapView;
        }
    };
}();
function initApp() {
    // START FOR AUTO LOAD MAP
    var view = router.currentView;
//    if(router.currentView.name == PAGE_MAP_VIEW){
//        autoLoad();
//    }
    // END FOR AUTO LOAD MAP
};

var autoInterval = null;
var autoLoad = function() {
    
    console.log('init autoLoad');
    
    window.clearInterval(autoInterval);
    
    autoInterval = setInterval(function() {
        console.log('DAO Template execute autoLoad map 3000ms.');
        OpenStreetMapUtil.updateInfoMarkersMap();
    }, 3000);
    
};
var container ;
var REQUIRE_UTILS_LIB = "require_utils";
var ROUTER_LIB = "router";
var TEXT_LIB = "text";
var DEPENDENCIES_LIB = [REQUIRE_UTILS_LIB,TEXT_LIB];
var router;
$(document).ready(function() {
    require(DEPENDENCIES_LIB, function() {
        require([ ROUTER_LIB ], function() {
            container = $("#container-content");
            router = new AppRouter();
            Backbone.history.start();
            initApp();
        });
//        var router = new Router();
//        Backbone.history.start();
        
    });
//	$("#selectMarkers").select2("readonly", true);
});